package com.weixun.utils;

public class StringUtils {
    public static String truncateStr(String _string, int _maxLength) {
        return truncateStr(_string, _maxLength, "..");
    }

    public static String truncateStr(String _string, int _maxLength, String _sExt) {
        if (_string == null) {
            return null;
        } else {
            String sExt = "..";
            if (_sExt != null) {
                sExt = _sExt;
            }

            int nExtLen = getBytesLength(sExt);
            if (nExtLen >= _maxLength) {
                return _string;
            } else {
                int nMaxLen = _maxLength - nExtLen + 1;
                char[] srcBuff = _string.toCharArray();
                int nLen = srcBuff.length;
                StringBuffer dstBuff = new StringBuffer(nLen + 2);
                int nGet = 0;

                for(int i = 0; i < nLen; ++i) {
                    char aChar = srcBuff[i];
                    boolean bUnicode = false;
                    int j = 0;
                    if (aChar == '&') {
                        for(j = i + 1; j < nLen && j < i + 9 && !bUnicode; ++j) {
                            char cTemp = srcBuff[j];
                            if (cTemp == ';') {
                                if (j == i + 5) {
                                    bUnicode = false;
                                    j = 0;
                                    break;
                                }

                                bUnicode = true;
                            }
                        }

                        ++nGet;
                    } else {
                        nGet += aChar > 127 ? 2 : 1;
                    }

                    if (nGet >= nMaxLen) {
                        if (nGet == _maxLength && i == nLen - 1) {
                            dstBuff.append(aChar);

                            while(i < j - 1) {
                                dstBuff.append(srcBuff[i + 1]);
                                ++i;
                            }

                            return dstBuff.toString();
                        } else {
                            dstBuff.append(sExt);
                            break;
                        }
                    }

                    dstBuff.append(aChar);

                    while(i < j - 1) {
                        dstBuff.append(srcBuff[i + 1]);
                        ++i;
                    }
                }

                return dstBuff.toString();
            }
        }
    }

    public static int getBytesLength(String _string) {
        if (_string == null) {
            return 0;
        } else {
            char[] srcBuff = _string.toCharArray();
            int nGet = 0;

            for(int i = 0; i < srcBuff.length; ++i) {
                char aChar = srcBuff[i];
                nGet += aChar > 127 ? 2 : 1;
            }

            return nGet;
        }
    }
}
